package com.crm.utils;

import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.interfaces.Claim;
import com.auth0.jwt.interfaces.DecodedJWT;

import java.util.*;

/**
 * @version 1.0
 * @author: CRM_SYSTEM
 * @date: 2022/3/30 22:16
 * @Description:
 */
public class JwtUtils {
    //设置过期时间
    private static final long EXPIRE_DATE = 30 * 60 * 100000;
    //token秘钥
    private static final String TOKEN_SECRET = "ZCEQIUBFKSJBFJH2020BQWE";


    public static String token(String phone,String username) {
        String token = "";
        try {
            //过期时间
            Date date = new Date(System.currentTimeMillis() + EXPIRE_DATE);
            //秘钥及加密算法
            Algorithm algorithm = Algorithm.HMAC256(TOKEN_SECRET);
            //设置头部信息
            Map<String, Object> header = new HashMap<>();
            header.put("typ", "JWT");
            header.put("alg", "HS256");
            //携带username，password信息，生成签名
            String[] array={username,phone};
            token = JWT.create()
                    .withHeader(header)
                    .withAudience(array)
//                    .withClaim("username", username)
//                    .withClaim("password", password)
                    .withExpiresAt(date)
                    .sign(algorithm);
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
        return token;
    }

    public static boolean verify(String token) {
        /**
         * @desc 验证token，通过返回true
         * @create 2019/1/18/018 9:39
         * @params [token]需要校验的串
         **/
        try {
            Algorithm algorithm = Algorithm.HMAC256(TOKEN_SECRET);
            JWTVerifier verifier = JWT.require(algorithm).build();
            DecodedJWT jwt = verifier.verify(token);
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }

    public static void main(String[] args) {
        String username = "zhangsan";
//        String password = "123";
        String phone = "124141";
        String token = token(phone,username);
        System.out.println(token);

        System.out.println(verify(token));
        String tok="eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJhdWQiOlsiemhhbmdzYW4iLCIxMjQxNDEiXSwicGFzc3dvcmQiOiIiLCJleHAiOjE2NDg5MjQ5NDUsInVzZXJuYW1lIjoiemhhbmdzYW4ifQ.U9TzhNyRTNxRKfxR_H6t7h04IsJHuiv9OZfGI9t5qO0";

        String s = JWT.decode(token).getAudience().get(0);
        System.out.println(s);
        String s1 = JWT.decode(token).getAudience().get(1);
        System.out.println(s1);
    }
}
